package com.yyi.springcloud.service.impl;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.yyi.springcloud.common.JedisClientSingle;
import com.yyi.springcloud.dao.AddtionFunctionMapper;
import com.yyi.springcloud.dao.CoordonateConfigMapper;
import com.yyi.springcloud.dao.SensorInfoMapper;
import com.yyi.springcloud.dao.TestDataMapper;
import com.yyi.springcloud.entities.*;
import com.yyi.springcloud.service.Local_AdditionFunctionService;
import com.yyi.springcloud.service.Local_TestDataService;
import com.yyi.springcloud.utils.JodaTimeUtil;
import com.yyi.springcloud.utils.JsonUtil;
import com.yyi.springcloud.utils.StringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

@Service
public class Local_TestDataServiceImpl implements Local_TestDataService {
	@Resource
	private TestDataMapper testDataMapper;

	@Resource
	private SensorInfoMapper sensorInfoDao;

	@Resource
	private CoordonateConfigMapper coordonateConfigMapper;

	@Resource
	private JedisClientSingle jedisClientSingle;
	@Resource
	private AddtionFunctionMapper addtionFunctionMapper;

	public TestDataMapper getTestDataMapper() {
		return testDataMapper;
	}

	public void setTestDataMapper(TestDataMapper testDataMapper) {
		this.testDataMapper = testDataMapper;
	}

	/**
	 * 1.根据条件查询测试数据
	 * 
	 * @param primarykey
	 * @param startdate
	 * @param enddate
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageInfo<TestDataModel> getTestDataByCondition(String primarykey, String startdate, String enddate,
                                                          int pageNum, int pageSize) {
		// 若pageSize=-1,则查询所有
		if (pageSize == -1) {
			pageNum = 1;
			pageSize = Integer.MAX_VALUE;
		}
		// 分页处理
		PageHelper.startPage(pageNum, pageSize);
		Example example = new Example(TestDataModel.class);
		Example.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(primarykey)) {
			criteria.andLike("primarykey", primarykey + "%");
		}
		// 根据开始时间和结束时间计算howlong的上下限
		try {
			String testDate = StringUtil.primaryKeyToDate(primarykey);
			int howLongStart = JodaTimeUtil.howLongSecond(testDate, startdate) / 3600;
			if (howLongStart < 0) {
				howLongStart = 0;
			}
			int howLongEnd = JodaTimeUtil.howLongSecond(testDate, enddate) / 3600;
			if (howLongEnd < 0) {
				howLongEnd = Integer.MAX_VALUE;
			}
			if (!StringUtils.isEmpty(startdate) && !StringUtils.isEmpty(enddate)) {
				criteria.andBetween("howlong", howLongStart, howLongEnd);
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("查询开始时间和结束时间失败");
		}

		List<TestDataModel> lists = testDataMapper.selectByExample(example);
		PageInfo<TestDataModel> pageInfo = new PageInfo<TestDataModel>(lists);

		return pageInfo;
	}

	/**
	 * 2.根据台位号,实验室编码和传感器编码查询该传感器所有的在测数据
	 * 
	 * @param labcode
	 * @param testunitno
	 * @param sensorno
	 * @return
	 */
	@Override
	public List<CurveVo> getSensorAllNowTestData(String labcode, String testunitno, String sensorno) {
		List<CurveVo> curveVoList = new ArrayList<CurveVo>();
		List<Double> sensorvalues = new ArrayList<Double>();// 该传感器所有测试数值
		List<String> relativetime = new ArrayList<String>();// 该传感器取数的所有相对时间
		List<String> absolutetime = new ArrayList<String>();// 该传感器取数的所有绝对时间
		String rediskey = labcode + "-" + testunitno + "-" + sensorno + "sensorvalues";
		// 1.获取某个台位所有的在测数据,用于判断是否有新数据
		List<TestDataVo> allNowTestData = new ArrayList<TestDataVo>();
		// 从缓存中取内容
		try {
			// 选择redis的第0个数据库
			// jedisClientSingle.select(0);
			String result = jedisClientSingle.get(rediskey);
			if (result != "" && result != null) {
				allNowTestData = JsonUtil.jsonToList(result, TestDataVo.class);
				// 如果有新数据
				// 查询数据库,获取最新的数据总数
				// int newTotal=testDataMapper.getCountNowTestData(labcode,
				// testunitno);
				int newTotal = 0;
				if (newTotal > allNowTestData.size()) {
					List<TestDataVo> allNowTestNewData = new ArrayList<TestDataVo>();
					allNowTestNewData = testDataMapper.getAllNowTestNewData(labcode, testunitno,
							String.valueOf(allNowTestData.size()));
					// 更新redis
					jedisClientSingle.append(rediskey, JsonUtil.list2json(allNowTestNewData));
				}
			} else {
				allNowTestData = testDataMapper.getAllNowTestData(labcode, testunitno);
				// 向缓存中添加数据
				jedisClientSingle.set(rediskey, JsonUtil.list2json(allNowTestData));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 2.查询使用的所有传感器
		SensorInfoModel sensorInfoModel = new SensorInfoModel();
		if (allNowTestData.size() > 0) {
			sensorInfoModel.setPrimarykey(allNowTestData.get(0).getPrimarykey());
		}
		sensorInfoModel.setSelected(1);// 只查询被选择的传感器
		List<SensorInfoModel> sensorInfoList = getSensorInfoByCondition(sensorInfoModel);
		for (SensorInfoModel sensorInfoModelTemp : sensorInfoList) {

			// 3.根据传感器编号查询传感器所有的值
			for (int i = 0; i < allNowTestData.size(); i++) {
				TestDataVo testDataVo = allNowTestData.get(i);
				// 3.1设置传感器的值
				String sensornoTemp = String.valueOf(sensorInfoModelTemp.getSensorno());
				if (!StringUtils.isEmpty(sensorno)) {
					sensornoTemp = sensorno;
				}
				String sensorValue = getSensorValueBySensorNo(testDataVo.getSensorvalue(), sensornoTemp);
				sensorvalues.add(Double.parseDouble(StringUtil.isRealNumber(sensorValue) ? sensorValue : "0"));
				// 3.2设置传感器的相对时间
				double seconds = testDataVo.getHowlong() * 3600;
				relativetime.add(String.valueOf(seconds));
				// 3.3设置传感器的绝对时间
				// 计算出当前数据的时间
				StringBuilder sb = new StringBuilder(testDataVo.getPrimarykey());
				DateTime dt = new DateTime(sb.insert(10, "T").substring(0, 19));
				// 四舍五入,保留0位小数
				String formatSeconds = new Formatter().format("%.0f", seconds).toString();
				dt = dt.plusSeconds(Integer.parseInt(formatSeconds));
				absolutetime.add(dt.toString("HH:mm:ss"));
			}
			CurveVo curveVo = new CurveVo();
			curveVo.setLabcode(labcode);
			curveVo.setTestunitno(Integer.parseInt(testunitno == null ? "0" : testunitno));
			// 设置传感器值,相对时间和绝对时间
			curveVo.setSensorvalues(sensorvalues);
			curveVo.setRelativetime(relativetime);
			curveVo.setAbsolutetime(absolutetime);
			curveVoList.add(curveVo);
			// 如果传入了传感器编码,则只查询该传感器的所有测试数据
			if (!StringUtils.isEmpty(sensorno)) {
				break;
			}
		}
		return curveVoList;
	}

	/**
	 * 3.根据实验室编码.primaryKey和传感器编号查询该传感器的所有测试数据
	 * 
	 * @param labcode
	 * @param primaryKey
	 * @param sensorno
	 * @return
	 */
	@Override
	public List<CurveVo> getSensorTestDataNow(String labcode, String primaryKey, String sensorno) {
		List<CurveVo> curveVoList = new ArrayList<CurveVo>();
		List<Double> sensorvalues = new ArrayList<Double>();// 该传感器所有测试数值
		List<String> relativetime = new ArrayList<String>();// 该传感器取数的所有相对时间
		List<String> absolutetime = new ArrayList<String>();// 该传感器取数的所有绝对时间
		// 台位
		String testunitno = primaryKey.substring(primaryKey.length() - 1);
		String rediskey = labcode + "-" + testunitno + "-" + sensorno + "sensorvalues";
		// 1.获取某个台位所有的在测数据,用于判断是否有新数据
		List<TestDataVo> allNowTestData = new ArrayList<TestDataVo>();
		Example example = new Example(TestDataModel.class);
		example.orderBy("howlong").asc();
		Example.Criteria criteria = example.createCriteria();
		criteria.andLike("primarykey", primaryKey + "%");

		// 从缓存中取内容
		try {
			// jedisClientSingle.select(0);
			String result = jedisClientSingle.get(rediskey);
			if (result != "" && result != null) {
				allNowTestData = JsonUtil.jsonToList(result, TestDataVo.class);
				// 如果有新数据,则更新redis
				// 查询数据库,获取最新的数据总数
				// int newTotal=testDataMapper.selectCountByExample(example);
				int newTotal = 0;
				if (newTotal > allNowTestData.size()) {
					List<TestDataVo> allNowTestNewData = new ArrayList<TestDataVo>();
					List<TestDataModel> testDataModelsTemp = testDataMapper.selectByExample(example);
					for (int i = 0; i < testDataModelsTemp.size(); i++) {
						TestDataVo testDataVoTemp = new TestDataVo();
						BeanUtils.copyProperties(testDataVoTemp, testDataModelsTemp.get(i));
						allNowTestNewData.add(testDataVoTemp);
					}
					// 更新redis
					jedisClientSingle.append(rediskey, JsonUtil.list2json(allNowTestNewData));
				}
			} else {
				List<TestDataModel> testDataModels = testDataMapper.selectByExample(example);
				for (int i = 0; i < testDataModels.size(); i++) {
					TestDataVo testDataVo = new TestDataVo();
					BeanUtils.copyProperties(testDataVo, testDataModels.get(i));
					allNowTestData.add(testDataVo);
				}
				// 向缓存中添加数据
				jedisClientSingle.set(rediskey, JsonUtil.list2json(allNowTestData));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 2.查询使用的所有传感器
		SensorInfoModel sensorInfoModel = new SensorInfoModel();
		sensorInfoModel.setPrimarykey(primaryKey);
		sensorInfoModel.setSelected(1);// 只查询被选择的传感器
		sensorInfoModel.setSensorno(sensorno == null ? null : Integer.parseInt(sensorno));
		//List<SensorInfoModel> sensorInfoList = getSensorInfoByCondition(sensorInfoModel);
		List<SensorInfoModel> sensorInfoList = addtionFunctionMapper.getSensorContinus();
		// 若不传入传感器编号,则查询所有传感器
		for (SensorInfoModel sensorInfoModelTemp : sensorInfoList) {
			String totaltime = "";
			// 3.根据传感器编号查询传感器所有的值
			for (int i = 0; i < allNowTestData.size(); i++) {
				TestDataVo testDataVo = allNowTestData.get(i);
				// 3.1设置传感器的值
				String sensornoTemp = String.valueOf(sensorInfoModelTemp.getSensorno());
				if (!StringUtils.isEmpty(sensorno)) {
					sensornoTemp = sensorno;
				}
				String sensorValue = getSensorValueBySensorNo(testDataVo.getSensorvalue(), sensornoTemp);
				sensorvalues.add(Double.parseDouble(StringUtil.isRealNumber(sensorValue) ? sensorValue : "0"));
				// 3.2设置传感器的相对时间(分钟)
				double seconds = testDataVo.getHowlong() * 60;
				// 四舍五入,保留0位小数
				String formatSeconds = new Formatter().format("%.0f", seconds).toString();
				relativetime.add(formatSeconds);
				// 3.3设置传感器的绝对时间
				// 计算出当前数据的时间
				String ss = testDataVo.getPrimarykey();
				StringBuilder sb = new StringBuilder(ss.replaceAll(" ",""));
				DateTime dt = new DateTime(sb.insert(10, "T").substring(0, 19));
				dt = dt.plusSeconds(Integer.parseInt(formatSeconds));
				absolutetime.add(dt.toString("HH:mm:ss"));
				// 3.4 设置测试总时间
				if (i == allNowTestData.size() - 1) {
					totaltime = formatSeconds;
				}
			}
			CurveVo curveVo = new CurveVo();
			curveVo.setLabcode(labcode);
			curveVo.setPrimaryKey(primaryKey);
			// 设置传感器值,相对时间和绝对时间
			curveVo.setSensorvalues(sensorvalues);
			curveVo.setRelativetime(relativetime);
			curveVo.setAbsolutetime(absolutetime);
			// 设置传感器的总测试时间
			curveVo.setTotaltime(totaltime);
			// 设置坐标系编号
		//	int coordinateno = sensorInfoModelTemp.getCoordinateno();
			//curveVo.setCoordinateno(coordinateno);
			if (sensorno.equals("64")){
				curveVo.setCoordinateno(2);
			}else if (sensorno.equals("65")){
				curveVo.setCoordinateno(2);
			}else if (sensorno.equals("66")){
				curveVo.setCoordinateno(2);
			}else if (sensorno.equals("67")){
				curveVo.setCoordinateno(2);
			}else if (sensorno.equals("35")){
				curveVo.setCoordinateno(7);
			}else if (sensorno.equals("33")){
				curveVo.setCoordinateno(3);
			}else if (sensorno.equals("89")){
				curveVo.setCoordinateno(6);
			}else if (sensorno.equals("90")){
				curveVo.setCoordinateno(4);
			}else if (sensorno.equals("91")){
				curveVo.setCoordinateno(5);
			}else if (sensorno.equals("92")){
				curveVo.setCoordinateno(5);
			}


			curveVo.setSensorno(sensorInfoModelTemp.getSensorno());
			curveVo.setTestunitno(Integer.parseInt(primaryKey.substring(19)));
			curveVoList.add(curveVo);
			// 如果传入了传感器编码,则只查询该传感器的所有测试数据
			if (!StringUtils.isEmpty(sensorno)) {
				break;
			}
		}
		return curveVoList;
	}

	/**
	 * 4.根据primaryKey和传感器编号查询传感器的最新一条测试数据 若 传感器编号为空,则查询所有的传感器
	 * 
	 * @param primaryKey
	 * @param sensorNo
	 * @return
	 */
	@Override
	public List<TestDataDto> getNewOneTestData(String primaryKey, String sensorNo) {
		// 通用mapper无法做到只查询符合条件的第一条数据
		// Example example = new Example(TestDataModel.class);
		// example.orderBy("howlong").desc();
		// if(!StringUtils.isEmpty(primaryKey)){
		// example.createCriteria().andLike("primarykey",primaryKey+"%");
		// }
		// TestDataModel testDataModel =
		// testDataMapper.selectOneByExample(example);
		List<TestDataDto> testDataDtoList = new ArrayList<TestDataDto>();
		TestDataModel testDataModel = testDataMapper.getNewOneTestData(primaryKey);
		if (testDataModel != null) {
			String[] split = testDataModel.getSensorvalue().split("@");
			for (int i = 1; i < split.length; i++) {
				if (!split[i].isEmpty()) {
					String[] split1 = split[i].split(":");
					TestDataDto testDataDto = new TestDataDto();
					testDataDto.setPrimarykey(primaryKey);
					testDataDto.setSensorno(split1[0]);
					if(split1.length<2||"N".equals(split1[1])){
						testDataDto.setSensorvalue("N");
					}else{
						testDataDto.setSensorvalue(split1[1]);
					}

					SensorVo sensorVo = new SensorVo();
					// 从缓存中取内容
					try {
						// jedisClientSingle.select(1);
						String redisKey=primaryKey + "-" + split1[0];
						String result = jedisClientSingle.hget("sensorUnit", redisKey);
						if (result != "" && result != null) {
							sensorVo = JsonUtil.jsonToPojo(result, SensorVo.class);
						} else {
							// 根据传感器No和primaryKey查询传感器单位(放入redis中)
							sensorVo = coordonateConfigMapper.selectSensorUnit(primaryKey, sensorNo);
							jedisClientSingle.hset("sensorUnit", redisKey, JsonUtil.object2json(sensorVo));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
                    //添加单位
					testDataDto.setSensorunit(sensorVo == null ? "" : sensorVo.getUnit());
					// 如果传感器编号不为空,则只查询该传感器的数据
					if (!StringUtils.isEmpty(sensorNo)) {
						if(sensorNo.equals(split1[0])){
							testDataDtoList.add(testDataDto);
							break;
						}else{
							continue;
						}

					}else{
						testDataDtoList.add(testDataDto);
					}
				}
			}
		}
		return testDataDtoList;
	}

	/**
	 * 5.根据primaryKey查询最新10条测试数据
	 * 
	 * @param primaryKey
	 * @return
	 */
	@Override
	public List<TestDataModel> getTestDataNewTop10(String primaryKey) {
		if (!StringUtils.isEmpty(primaryKey)) {
			// 查询最新的10条数据
			return testDataMapper.getAllNowTestDataNew(primaryKey, "10");
		} else {
			return null;
		}
	}

	/**
	 * 6.根据primaryKey和传感器编号查询传感器的所有测试数据
	 * 
	 * @param primaryKey
	 * @param sensorNo
	 * @return
	 */
	@Override
	public List<TestDataDto> getAllTestDataByCondition(String primaryKey, String sensorNo) {
		List<TestDataDto> testDataDtoList = new ArrayList<TestDataDto>();
		String redisKey = primaryKey.replaceAll(":", "-").trim() + "--" + sensorNo;
		// 查询redis缓存
		// 从缓存中取内容
		try {
			// jedisClientSingle.select(1);
			String result = jedisClientSingle.get(redisKey);
			if (result != "" && result != null) {
				testDataDtoList = JsonUtil.jsonToList(result, TestDataDto.class);
			} else {
				Example example = new Example(TestDataModel.class);
				Example.Criteria criteria = example.createCriteria();
				if (StringUtils.isEmpty(primaryKey) || StringUtils.isEmpty(sensorNo)) {
					return null;
				}
				// 传感器primarykey
				criteria.andLike("primarykey", primaryKey + "%");
				List<TestDataModel> testDataModels = testDataMapper.selectByExample(example);
				List<TestDataDto> finalTestDataDtoList = testDataDtoList;
				testDataModels.stream().forEach(testDataModel -> {
					if (testDataModel != null) {
						String[] split = testDataModel.getSensorvalue().split("@");
						for (int i = 0; i < split.length; i++) {
							if (!split[i].isEmpty()) {
								String[] split1 = split[i].split(":");
								if (split1[0].equals(sensorNo)) {
									TestDataDto testDataDto = new TestDataDto();
									testDataDto.setPrimarykey(primaryKey);
									testDataDto.setSensorno(split1[0]);
									testDataDto.setSensorvalue("N".equals(split1[1]) ? "0" : split1[1]);
									finalTestDataDtoList.add(testDataDto);
								}

							}
						}
					}
				});
				testDataDtoList = finalTestDataDtoList;
				// 存入redis
				jedisClientSingle.set(redisKey, JsonUtil.list2json(testDataDtoList));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return testDataDtoList;
	}

	/**
	 * 12.根据primaryKey,传感器分组编号,开始时间和结束时间等查询并统计传感器信息(统计值专用)
	 * 
	 * @return
	 */
	@Override
	public List<TestDataStatisticsVo> getStatisticsSensorInfoByCondition(String primaryKey, String groupNo,
			String start, String end) {
		Example example = new Example(SensorInfoModel.class);
		Example.Criteria criteria = example.createCriteria();
		// 设置只查询指定列
		example.selectProperties("primarykey", "groupno", "sensorno", "name", "selected", "visible", "colorno");
		example.setOrderByClause("sensorno");
		if (StringUtils.isEmpty(primaryKey) || StringUtils.isEmpty(groupNo)) {
			return null;
		}
		// 传感器primarykey
		criteria.andLike("primarykey", primaryKey + "%");
		// 传感器相对编号
		criteria.andEqualTo("groupno", groupNo);
		// 传感器是否被选择
		criteria.andEqualTo("selected", 1);
		// 添加时间节点的数据查询
		double startTime = Double.parseDouble(start);
		startTime = startTime / 60.0;
		// criteria.andLessThan("howlong", startTime);

		double endTime = Double.parseDouble(end);
		endTime = endTime / 60.0;
		// criteria.andGreaterThan("howlong", endTime);
		List<SensorInfoModel> sensorInfoModels = sensorInfoDao.selectByExample(example);
		// 使用lambda表达式遍历list
		// sensorInfoModels.stream().forEach(sensorInfoModel -> {
		// // 根据时间范围,primaryKey和传感器编号查询所有的传感器数据
		// List<TestDataDto> allTestDataByCondition =
		// getStatisticsTestDataByCondition(primaryKey,
		// sensorInfoModel.getSensorno() + "", startTime, endTime);
		// // TODO
		// // 计算该传感器在某个时间段内的最大值,最小值,积分平均值和差值
		//
		// });
		// System.out.println("////////////////////////////////////////////////////////");
		// System.out.println("长度：" + sensorInfoModels.size());

		List<TestDataStatisticsVo> dataStatisticsVos = new ArrayList<TestDataStatisticsVo>();
		for (SensorInfoModel sensorInfoModel : sensorInfoModels) {
			TestDataStatisticsVo statisticsTestData = getStatisticsTestDataByCondition(primaryKey,
					sensorInfoModel.getSensorno() + "", startTime, endTime);
			statisticsTestData.setSensorName(sensorInfoModel.getName());
			dataStatisticsVos.add(statisticsTestData);
		}
		// List<TestDataDto> allTestDataByCondition =
		// getStatisticsTestDataByCondition(primaryKey,
		// sensorInfoModels.get(0).getSensorno() + "", startTime, endTime);

		return dataStatisticsVos;
	}


	/**
	 * 13.根据开始时间,结束时间,primaryKey,sensorNo查询测试数据
	 * 
	 * @param primaryKey
	 * @param sensorNo
	 * @param start
	 * @param end
	 * @return
	 */
	@Override
	public TestDataStatisticsVo getStatisticsTestDataByCondition(String primaryKey, String sensorNo, double start,
			double end) {
		if (StringUtils.isEmpty(primaryKey) || StringUtils.isEmpty(sensorNo)) {
			return null;
		}

		// 根据pk和时长区间范围查询对应传感器编号的数据
		Example example = new Example(TestDataModel.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andLike("primarykey", primaryKey + "%");
		criteria.andGreaterThanOrEqualTo("howlong", start);
		criteria.andLessThanOrEqualTo("howlong", end);
		List<TestDataModel> testDataModels = testDataMapper.selectByExample(example);

		// 遍历查询结果进行字符串切分，封装传感器数据
		List<TestDataDto> finalTestDataDtoList = new ArrayList<TestDataDto>();
		testDataModels.stream().forEach(testDataModel -> {
			if (testDataModel != null) {
				String[] split = testDataModel.getSensorvalue().split("@");
				for (int i = 0; i < split.length; i++) {
					if (!split[i].isEmpty()) {
						String[] split1 = split[i].split(":");
						if (split1[0].equals(sensorNo)) {
							TestDataDto testDataDto = new TestDataDto();
							testDataDto.setPrimarykey(primaryKey);
							testDataDto.setSensorno(split1[0]);
							testDataDto.setSensorvalue("N".equals(split1[1]) ? "0" : split1[1]);
							finalTestDataDtoList.add(testDataDto);
						}
					}
				}
			}
		});

		double max = finalTestDataDtoList.stream().mapToDouble(TestDataDto::getSensorvalue4Double).max().getAsDouble();
		double min = finalTestDataDtoList.stream().mapToDouble(TestDataDto::getSensorvalue4Double).min().getAsDouble();
		double average = finalTestDataDtoList.stream().mapToDouble(TestDataDto::getSensorvalue4Double).average()
				.getAsDouble();
		double difference = subDouble(max, min);
		TestDataStatisticsVo testDataStatisticsVo = new TestDataStatisticsVo(sensorNo, max, min, average, 0.0,
				difference);

		System.out.println("=========计算结果============================");
		System.out.println("最大值：" + max);
		System.out.println("最小值：" + min);
		System.out.println("平均值：" + average);
		System.out.println("差值：" + difference);
		System.out.println("=========计算结果结束============================");

		return testDataStatisticsVo;
	}

	// 根据条件查询传感器信息
	public List<SensorInfoModel> getSensorInfoByCondition(SensorInfoModel sensorInfoModel) {
		Example example = new Example(SensorInfoModel.class);
		Example.Criteria criteria = example.createCriteria();
		// 设置只查询指定列
		example.selectProperties("primarykey", "sensorno", "name", "selected", "visible", "colorno", "coordinateno");
		example.setOrderByClause("sensorno");
		if (sensorInfoModel == null) {
			return null;
		}

		if (!StringUtils.isEmpty(sensorInfoModel.getPrimarykey())) {
			criteria.andLike("primarykey", sensorInfoModel.getPrimarykey() + "%");
		}
		// 传感器相对编号
		if (sensorInfoModel.getSensorno() != null) {
			criteria.andEqualTo("sensorno", sensorInfoModel.getSensorno());
		}
		// 传感器是否被选择
		if (sensorInfoModel.getSelected() != null) {
			criteria.andEqualTo("selected", sensorInfoModel.getSelected());
		}
		// 是否可见
		// criteria.andEqualTo("visible",1);
		return sensorInfoDao.selectByExample(example);
	}

	// 从所有的传感器测试值中查询某传感器编号对应的值
	public String getSensorValueBySensorNo(String sensorValue, String sensorNo) {
		int start = StringUtils.ordinalIndexOf(sensorValue, "@" + sensorNo, 1);
		int end = StringUtils.ordinalIndexOf(sensorValue, "@" + (Integer.parseInt(sensorNo) + 1), 1);
		if (end != -1) {
			return sensorValue.substring(start + sensorNo.length() + 2, end);
		} else {
			return sensorValue.substring(start + sensorNo.length() + 2);
		}
	}

	/**
	 * 减法运算：解决double运算精度丢失问题
	 * 
	 * @Description:
	 * @author 高杨
	 * @date 2018年9月18日 下午3:47:03
	 * @return double
	 */
	private double subDouble(double m1, double m2) {
		BigDecimal p1 = new BigDecimal(Double.toString(m1));
		BigDecimal p2 = new BigDecimal(Double.toString(m2));
		return p1.subtract(p2).doubleValue();
	}

	@Override
	public List<TestDataModel> getTestData2Excel(String primarykey, String startdate, String enddate) {
		Example example = new Example(TestDataModel.class);
		Example.Criteria criteria = example.createCriteria();

		if (!StringUtils.isEmpty(primarykey)) {
			criteria.andLike("primarykey", primarykey + "%");
		}

		if (StringUtils.isNotBlank(startdate) && StringUtils.isNotBlank(enddate)) {
			double start = Double.parseDouble(startdate) / 60.0;
			double end = Double.parseDouble(enddate) / 60.0;
			criteria.andGreaterThanOrEqualTo("howlong", start);
			criteria.andLessThanOrEqualTo("howlong", end);
		}

		List<TestDataModel> lists = testDataMapper.selectByExample(example);
		return lists;
	}

}
